package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-23
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient iotdaClient;
    @Autowired
    private HuaWeiIotConfigProperties huaweiIotConfigProperties;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询设备信息列表
     *
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }
    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //对接华为云api,获得信息
        ListProductsResponse listProductsResponse = iotdaClient.listProducts(new ListProductsRequest());
        //判断获取产品列表是否成功
        if (listProductsResponse.getHttpStatusCode() != 200) {
            //没有成功,报异常
            throw new BaseException("获取产品列表失败");
        }

        //将获取到的产品列表保存到redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(listProductsResponse.getProducts()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从Redis查询产品列表JSON字符串
        String productListJson = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if(StringUtils.isBlank(productListJson)) {
            return Collections.emptyList();
        }

        //解析JSON为产品列表
        List<ProductSummary> productList = JSONUtil.toList(productListJson, ProductSummary.class);

        //遍历产品列表，转为前端需要的数据类型
        List<ProductVo> productVoList = productList.stream().map(x -> {
            return ProductVo.builder().productKey(x.getProductId()).productName(x.getName()).build();
        }).collect(Collectors.toList());

        return productVoList;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDevice(DeviceDto dto) {
        System.out.println(dto);
        //使用雪花算法生成设备的标识码
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        //设备备注名称
        String nickname = dto.getNickname();
        //检查设备名是否重复
        Long countByDeviceName = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName())
                .count();
        if (countByDeviceName > 0) {
            throw new BaseException("设备名重复");
        }
        //检查当前位置是否绑定过相同产品
        Long count = this.lambdaQuery().eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey())
                .count();
        if (count > 0) {
            throw new BaseException("相同类型的设备已经有了,请勿重复添加");
        }
        //注册设备到华为云IOT平台
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setProductId(dto.getProductKey());
        addDevice.setDeviceName(dto.getDeviceName());
        //雪花算法值当做唯一设备标识码
        addDevice.setNodeId(nodeId);
        AuthInfo authInfo = new AuthInfo();
        //uuid当做唯一设备密钥
        String secret = IdUtil.simpleUUID();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        addDeviceRequest.setBody(addDevice);
        addDevice.setDescription(nickname);//设备备注名称（设备描述）
        AddDeviceResponse response = iotdaClient.addDevice(addDeviceRequest);
        //注意这个IOT的接口响应201表示创建成功，不是传统的200
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("注册设备到华为IOT失败");
        }
        //保存设备到表中
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setNodeId(nodeId);//前面生成的设备标识码
        device.setIotId(response.getDeviceId());//设备ID由物联网平台分配获得，生成规则为product_id + _ + node_id拼接而成
        device.setNickname(nickname);//设备备注名称（设备描述）
        device.setDeviceDescription(nickname);//设备备注名称（设备描述）
        device.setSecret(secret);//前面生成的设备密钥

        String productName = this.getProductNameFromCache(dto.getProductKey());
        device.setProductName(productName);//产品名称
        this.save(device);
    }

    /**
     * 查询设备详细数据
     *
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(DeviceDto dto) {
        //查询数据库表中的数据
        Device device = this.lambdaQuery().eq(Device::getIotId, dto.getIotId()).one();
        //判断查到的数据是否为空
        if (device == null) {
            throw new BaseException("没有查询到的设备");
        }
        //拷贝数据到Vo中
        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        detailVo.setGmtCreate(device.getCreateTime());
        detailVo.setDeviceSecret(device.getSecret());
        detailVo.setRegion(huaweiIotConfigProperties.getRegionId());
        //根据用户id找用户名字
        SysUser sysUser = sysUserService.selectUserById(device.getId());
        detailVo.setCreator(sysUser.getUserName());
        //调用华为云
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.setDeviceId(dto.getIotId());
        ShowDeviceResponse showDeviceResponse = iotdaClient.showDevice(showDeviceRequest);
        if (showDeviceResponse.getHttpStatusCode() != 200) {
            throw new BaseException("获取设备详细信息失败");
        }
        detailVo.setDeviceStatus(showDeviceResponse.getStatus());
        detailVo.setFirmwareVersion(showDeviceResponse.getFwVersion());
        //获取设备激活时间
        String activeTime = showDeviceResponse.getActiveTime();
        if (StringUtils.isNotBlank(activeTime)) {
            LocalDateTime gmtActive = OffsetDateTime.parse(activeTime)
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            detailVo.setGmtActive(gmtActive);
        }
        return detailVo;
    }

    /**
     * 从缓存中根据产品ID获取产品名
     *
     * @param productAppId
     * @return
     */
    private String getProductNameFromCache(String productAppId) {
        //从Redis查询产品列表JSON字符串
        String productListJson = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StrUtil.isBlank(productListJson)) {
            return null;
        }

        //解析JSON为产品列表
        List<ProductSummary> productList = JSONUtil.toList(productListJson, ProductSummary.class);
        ProductSummary product = productList.stream().filter(x -> productAppId.equals(x.getProductId())).findFirst().get();
        return product.getName();
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param dto
     */
    @Override
    public JSONObject queryProductModelInfo(DeviceDto dto) {
        //从华为云中获取信息
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(dto.getProductKey());
        ShowProductResponse showProductResponse = iotdaClient.showProduct(showProductRequest);
        if (showProductResponse.getHttpStatusCode() != 200) {
            throw new BaseException("获取参数异常");
        }
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        if (CollUtil.isNotEmpty(serviceCapabilities)) {
            JSONObject productModelInfo = JSONUtil.parseObj(serviceCapabilities.get(0));
            return productModelInfo;
        }
        return null;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param dto
     */
    @Override
    public Map queryDevicePropertyStatus(DeviceDto dto) {
        //1.根据产品id及设备名称获取设备id
        Device device = this.lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getDeviceName, dto.getDeviceName()).one();
        //2.获取华为云中的数据
        ShowDeviceShadowRequest showDeviceShadowRequest = new ShowDeviceShadowRequest();
        showDeviceShadowRequest.setDeviceId(device.getIotId());
        ShowDeviceShadowResponse showDeviceShadowResponse = iotdaClient.showDeviceShadow(showDeviceShadowRequest);
        if (showDeviceShadowResponse.getHttpStatusCode() != 200) {
            throw new BaseException("获取参数失败");
        }
        List<DeviceShadowData> shadow = showDeviceShadowResponse.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            throw new BaseException("获取shadow参数失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String,Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime eventTime = OffsetDateTime.parse(shadow.get(0).getReported().getEventTime(),
                        DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX")
                )
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("identifier",k);
            map.put("value",v);
            map.put("time",eventTime);
            list.add(map);
        });

        Map<String,Object> propertyStatusInfo = new HashMap<>();
        propertyStatusInfo.put("propertyStatusInfo", list);

        Map<String,Object> result = new HashMap<>();
        result.put("list",propertyStatusInfo);

        return result;

    }

    /**
     * 修改设备备注名称
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDevice(DeviceDto dto) {
        //数据库修改
        this.lambdaUpdate().eq(Device::getId,dto.getId())
                .eq(Device::getDeviceName, dto.getDeviceName())
                .eq(Device::getProductKey,dto.getProductKey())
                .set(Device::getNickname,dto.getNickname())
                .set(Device::getBindingLocation,dto.getBindingLocation())
                .set(Device::getDeviceDescription,dto.getDeviceDescription())
                .set(Device::getLocationType,dto.getLocationType())
                .set(Device::getPhysicalLocationType,dto.getPhysicalLocationType())
                .set(Device::getRemark,dto.getRemark())
                .update();
        //华为云修改
        Device device = lambdaQuery().eq(Device::getId, dto.getId()).one();
        UpdateDeviceRequest updateDeviceRequest = new UpdateDeviceRequest();
        updateDeviceRequest.setDeviceId(device.getIotId());
        UpdateDevice updateDevice =new UpdateDevice();
        updateDevice.setDescription(dto.getNickname());
        updateDeviceRequest.setBody(updateDevice);
        UpdateDeviceResponse updateDeviceResponse = iotdaClient.updateDevice(updateDeviceRequest);
        if (!Arrays.asList(200, 204).contains(updateDeviceResponse.getHttpStatusCode())) {
            throw new BaseException("修改华为云设备失败，状态码：" + updateDeviceResponse.getHttpStatusCode());
        }
    }

    /**
     * 删除设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(DeviceDto dto) {
        //删除数据库中的
        LambdaQueryWrapper<Device> deviceQueryWrapper = new LambdaQueryWrapper<>();
                deviceQueryWrapper.eq(Device::getIotId, dto.getIotId())
                .eq(Device::getProductKey, dto.getProductKey());
        this.remove(deviceQueryWrapper);
        //删除华为云中的
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.withDeviceId(dto.getIotId());
        DeleteDeviceResponse deleteDeviceResponse = iotdaClient.deleteDevice(deleteDeviceRequest);

    }
}